# coding = utf-8
import datetime

from django.db import transaction
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from rest_framework.viewsets import ModelViewSet

from base.api.utils import update_customer_points
from base.models import CustomSupplier
from finance.api.utils import update_account
from points.models import PointType, Recharge, PointConsume
from .serializers import PointTypeSerializer, RechargeSerializer, PointConsumeSerializer


class PointTypeListAPIView(ListAPIView):
    """积分类型"""
    permission_classes = ()
    queryset = PointType.objects.all()
    serializer_class = PointTypeSerializer


class PointTypeViewSet(ModelViewSet):
    """积分类型"""
    permission_classes = ()
    queryset = PointType.objects.all()
    serializer_class = PointTypeSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class RechargeViewSet(ModelViewSet):
    """客户充值"""
    permission_classes = ()
    queryset = Recharge.objects.all()
    serializer_class = RechargeSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)
        category = self.request.query_params.get("category", None)

        if name:
            queryset = queryset.filter(customer__name__contains=name)

        if category:
            queryset = queryset.filter(category=int(category))

        return queryset

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                # 减少账号金额
                update_account(instance.account_id, instance.money)
                # 减少客户账号积分
                update_customer_points(instance.customer_id, -1 * instance.active_point, -1 * instance.member_point)
                self.perform_destroy(instance)

            except Exception as e:
                print(e)
                transaction.savepoint_rollback(save_id)

            transaction.savepoint_commit(save_id)

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.update_points(select_ids)
        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)

    def update_points(self, select_ids):
        objs = self.serializer_class.Meta.model.objects.filter(id__in=select_ids)
        for obj in objs:
            # 减少账号金额
            update_account(obj.account_id, obj.money)
            # 撤销积分
            update_customer_points(obj.customer_id, -1 * obj.active_point, -1 * obj.member_point)


class PointConsumeViewSet(ModelViewSet):
    permission_classes = ()
    queryset = PointConsume.objects.all()
    serializer_class = PointConsumeSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)
        category = self.request.query_params.get("category", None)
        search_date = self.request.query_params.getlist("search_date[]", None)

        if name:
            queryset = queryset.filter(customer__name__contains=name)

        if category:
            queryset = queryset.filter(category=int(category))

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(update_time__date__range=(search_date[0], search_date[1]))

        return queryset


class CustomerPointsListAPIView(APIView):
    """活动积分和会员积分"""
    # authentication_classes = ()
    permission_classes = ()
    pagination_class = None

    def get(self, request, *args, **kwargs):
        customer_id = request.query_params.get("customer")
        if not customer_id:
            return Response({"return_code": -1})

        obj = CustomSupplier.objects.filter(id=int(customer_id)).first()

        data = dict()
        data_list = []
        if obj:
            if obj.member_point and obj.member_point > 0:
                member_point_data = {
                    'code': obj.name + '会员积分',
                    'order_time': datetime.datetime.now().date(),
                    'customer_name': obj.name,
                    'saler_name': '',
                    'total_amount': obj.member_point * -1,
                    'amount': 0,
                    'norecv_amount': obj.member_point * -1,
                    'flag_name': '会员积分',
                    'remark': '会员积分支付',
                    'category': 2
                }
                data_list.append(member_point_data)

            if obj.active_point > 0:
                active_point_data = {
                    'code': obj.name + '活动积分',
                    'order_time': datetime.datetime.now().date(),
                    'customer_name': obj.name,
                    'saler_name': '',
                    'total_amount': obj.active_point * -1,
                    'amount': 0,
                    'norecv_amount': obj.active_point * -1,
                    'flag_name': '活动积分',
                    'remark': '活动积分支付',
                    'category': 3
                }
                data_list.append(active_point_data)

            data["return_code"] = 0
            data["results"] = data_list
        return Response(data)
